package woaini.wind.bot.api.holidays;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.TypeReference;
import lombok.experimental.UtilityClass;
import woaini.wind.bot.api.holidays.dto.HolidaysResponseDTO;
import woaini.wind.bot.api.holidays.dto.HolidaysResponseDayDTO;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import java.util.LinkedHashMap;

/**
 * 节假日 API
 *
 * @see HolidaysApi
 * @author yefeng {@date 2025-01-02 14:49:05}
 */
@UtilityClass
public class HolidaysApi {

  public static final String url = "https://api.jiejiariapi.com/v1/holidays/";

  /**
   * 获取节假日信息
   *
   * @param year 年份
   * @author yefeng {@date 2025-01-02 15:02:20}
   * @since 1.0
   * @return {@link HolidaysResponseDTO }
   */
  public LinkedHashMap<String, HolidaysResponseDayDTO> getHolidays(Integer year) {

//    String body = HttpRequest.get(url + year)
//      .header("User-Agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:134.0) Gecko/20100101 Firefox/134.0")
//      .setSSLSocketFactory(getSSLSocketFactory()).execute().body();
//    if (StrUtil.isEmpty(body)){
//      return null;
//    }
    String body = FileUtil.readString("/home/xiuyuan/tmp/holidays.json", StandardCharsets.UTF_8);

    return JSONObject.parseObject(body, new TypeReference<LinkedHashMap<String,HolidaysResponseDayDTO>>() {

    });

  }

  /**
   * 忽略https证书验证
   * @return
   */
  public static SSLSocketFactory getSSLSocketFactory() {
    try {
      SSLContext sslContext = SSLContext.getInstance("SSL");
      sslContext.init(null, getTrustManager(), new SecureRandom());
      return sslContext.getSocketFactory();
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }

  private static TrustManager[] getTrustManager() {
    TrustManager[] trustAllCerts = new TrustManager[]{
      new X509TrustManager() {
        //检查客户端证书，若不信任该证书抛出异常，咱们自己就是客户端不用检查
        @Override
        public void checkClientTrusted(X509Certificate[] chain, String authType) {
        }
        //检查服务器的证书，若不信任该证书抛出异常，可以不检查默认都信任
        @Override
        public void checkServerTrusted(X509Certificate[] chain, String authType) {
        }

        //返回受信任的X509证书数组
        @Override
        public X509Certificate[] getAcceptedIssuers() {
          return new X509Certificate[]{};
        }
      }
    };
    return trustAllCerts;
  }
}
